<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class config extends Admin_Controller {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );

    function __construct() {
        parent::__construct();
        $this->load->model("muser");
        $this->load->model("mconfig");

		$this->resCode = $this->mconfig->resCode;
        $this->url_index = admin_url() . "config";
        $this->folder_upload = "dataupload/config/";
        $this->url_edit = $this->url_index . "/edit/";
        $this->url_delete = $this->url_index . "/delete/";
        $this->url_add = $this->url_index . "/edit/0";
    }

    public function index() {
		if (!$this->permission->check("insert", $this->resCode))
			return $this->nopermission();
        $data = array();
        $data['tresource'] = $this->mresource->get($this->resCode,'RES_CODE');
		$data['config'] = array();
		$this->db->order_by("CONF_ORDER asc");
		$configs = $this->mconfig->gets();
		foreach($configs as $config){
			$data['config'][$config->CONF_GROUP][] = $config;
		}
		$post = $this->input->post('conf');
		if ($post) {
			$arr_update = array();
			foreach($post as $k=>$v){
				$arr_update[] = array(
					'CONF_CODE'=>$k,
					'CONF_VALUE'=>$v,
				);
			}
			$this->db->update_batch('config', $arr_update, 'CONF_CODE');
			$this->build_file();			
			redirect($this->url_index);
		}
		$this->theme_data["main"] = "config/edit";
        $this->template->viewAdmin($this->theme_data, $data);
    }
	
	function build_file(){
		$this->load->helper('file');
		$configs = $this->mconfig->gets();
		$temp = array();
		$data = "<?php\n";
		$data.= "if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n";
		foreach($configs as $config){
			$data.= "\$config['".$config->CONF_CODE."'] = '".$config->CONF_VALUE."';\n";
		}
		$file_name = APPPATH.'config/mconfig.php';
		$data.= "?>";
		if(!write_file('./'.$file_name, $data)){
		die("Unable to write the file ".$file_name);
		}
	}
}
